﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using DB.SqlHelper;
using Framework.Common.Common;
using Mode;

namespace Framework.DataAccess
{
    // 阅卷类
    public class ReadOver : candidate_table
    {
        // 参考者的员工信息
        private member_view member;
        // 考场信息
        private examination_table examination;
        // 答题卡列表
        private IList<sheet_table> sheet_list;
        // 是否有问答题
        private bool hasQuery = false;
        

        private readonly DbInstance db;
        public ReadOver(int candidtaeID)
        {
            db = DbManager.GetDbInstance();

            // 取得应考者信息
            get_candidate_by_id(candidtaeID);

        }

        // 取得参考者信息
        private void get_candidate_by_id(int candid)
        {
            string sql = "SELECT * FROM candidate_table WHERE ID="+candid;
            DataView view = db.ExecuteDataTableBySql(sql).DefaultView;
            if (view.Count != 1)
                throw new Exception("获取考生参考信息出错.\n[candidtate_table]:"+candid);
            
            this.id = view[0]["id"].ToInt();
            this.score = view[0]["score"].ToInt();
            this.time = view[0]["time"].ToInt();
            this.date = Convert.ToDateTime(view[0]["date"]);
            this.status = view[0]["status"].ToInt();

            //if (this.status != -1 && this.status != 0)
            //    throw new Exception("当前考生试卷已阅.\n[candidate_table]:"+ candid);

            // 取得成员信息
            get_member_safe(view[0]["member"].ToInt());
            // 取得考场信息
            get_examination_table(view[0]["examination"].ToInt());
            // 取得答题卡信息
            get_sheet_table(this.id);
        }

        // 取得成员信息
        private void get_member_safe( int memberID )
        {
            string sql = "SELECT * FROM member_view WHERE M_ID="+ memberID;
            DataView view = db.ExecuteDataTableBySql(sql).DefaultView;

            if(view.Count != 1)
                throw new Exception("获取成员信息出现异常.\n[member_view]:"+memberID);

            this.member = new member_view();
            this.member.M_ID = view[0]["M_ID"].ToInt();
            this.member.M_NAME = view[0]["M_NAME"].ToString();
            this.member.M_SEX = view[0]["M_SEX"].ToInt();
            this.member.M_PHONE = view[0]["M_PHONE"].ToString();
            this.member.M_DEPAT = view[0]["M_DEPAT"].ToString();
            this.member.M_CODE = view[0]["M_CODE"].ToString();
            this.member.M_EMAIL = view[0]["M_EMAIL"].ToString();
            this.member.M_DATE = Convert.ToDateTime( view[0]["M_DATE"] );
            this.member.M_STATUS = view[0]["M_STATUS"].ToInt();
            this.member.A_ID = view[0]["A_ID"].ToInt();
            this.member.A_NAME = view[0]["A_NAME"].ToString();
            this.member.A_LEVEL = view[0]["A_LEVEL"].ToInt();
            this.member.R_ID = view[0]["R_ID"].ToInt();
            this.member.R_NAME = view[0]["R_NAME"].ToString();
            this.member.R_POWER = view[0]["R_POWER"].ToInt();

        }

        // 取得参考者对应的考场信息.
        private void get_examination_table( int examID)
        {
            string sql = "SELECT * FROM examination_table WHERE id=" + examID;
            DataView view = db.ExecuteDataTableBySql(sql).DefaultView;


            if (view.Count != 1)
                throw new Exception("考场信息获取出错.\n[examination_table]:" + examID);

            examination = new examination_table();
            examination.id = view[0]["id"].ToInt();
            examination.name = view[0]["name"].ToString();
            examination.model = view[0]["model"].ToInt();
            examination.date = Convert.ToDateTime(view[0]["date"]);
            examination.begin = Convert.ToDateTime(view[0]["begin"]);
            examination.end = Convert.ToDateTime(view[0]["end"]);
            examination.time = view[0]["time"].ToInt();
            examination.pass = view[0]["pass"].ToInt();
            examination.status = view[0]["status"].ToInt();

            //if (examination.status != 0)
            //    throw new Exception("考场已被禁用,请与管理员联系. [examination_table]:" + examination.id);
        }

        // 取得答题卡表
        private void get_sheet_table(int candidateID)
        {
            string sql = "SELECT * FROM sheet_table WHERE candidate = " + candidateID;
            IDataReader reader = db.ExecuteReaderBySql(sql);
            sheet_list = DbManager.FillList<sheet_table>(reader);
            if (!reader.IsClosed) reader.Close();
        }

        // 取得作答者的填答情况
        private List<reply_table> get_reply( sheet_table item)
        {
            string sql = "SELECT * FROM REPLY_TABLE WHERE sheet="+item.id+" order by answerid" ;
            IDataReader rander = db.ExecuteReaderBySql(sql);
            IList<reply_table> reply = DbManager.FillList<reply_table>(rander);
            if (!rander.IsClosed) rander.Close();

            return reply.ToList<reply_table>();
        }

        // 取得标准答案
        private List<answer_table> get_answer(sheet_table item)
        {
            // 取得正确答案
            string sql = "SELECT * FROM ANSWER_TABLE WHERE topic = " + item.topic + " AND  [right]=1 order by id";
            IDataReader rander = db.ExecuteReaderBySql(sql);
            IList<answer_table> answer = DbManager.FillList<answer_table>(rander);
            if (!rander.IsClosed) rander.Close();

            return answer.ToList<answer_table>();
        }

        // 比对答案
        private bool compare_answer(List<answer_table> answer, List<reply_table> reply, int type)
        {
            bool result = true;

            if (answer.Count != reply.Count)
                return false;

            for (int index = 0; index < answer.Count; index++)
            {
                if (type == 4)
                {   // 阅填空题
                    if (!answer[index].answer.Equals(reply[index].reply))
                    {
                        result = false;
                        break;
                    }
                }
                else
                {   // 阅问答题
                    if (answer[index].id != reply[index].answerid)
                    {
                        result = false;
                        break;
                    }
                }
            }
            return result;
        }

        //  阅卷
        public void ReadTopic()
        {
            foreach (sheet_table item in sheet_list)
            {
                // 只阅 单选, 多选, 填空, 不阅,打字,问答.
                switch (item.topictype)
                {
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        bool right = compare_answer(get_answer(item), get_reply(item), item.topictype);
                        if (right)      // 正确,计算单题得分.
                        {
                            score += item.full;
                            string sql = "update sheet_table set score=" + item.full + " where id=" + item.id;
                            int v = db.ExecuteNonQueryBySql(sql);
                            if (v != 1)
                                throw new Exception("阅卷更新分数出错.[sheet_table]:" + item.id);
                        }
                        break;
                    case 5:
                        if (!hasQuery)
                            hasQuery = true;
                        break;
                }
            }

            // 更新阅卷状态.
            string upsql = "UPDATE candidate_table SET [score]=" + score + " , [status]={0} WHERE id=" + this.id;

            if (hasQuery)
            {
                int v = db.ExecuteNonQueryBySql(String.Format(upsql, 0));
            }
            else 
            {
                // 计算合格率与分数
                string sumsql = "SELECT sum([score]) AS score, sum([full]) AS [full] from sheet_table WHERE candidate =" + this.id;
                DataView view = db.ExecuteDataTableBySql(sumsql).DefaultView;

                float pass = examination.pass * view[0]["full"].ToInt();
                pass /= 100.00F;
                float tscore = (float)view[0]["score"].ToInt();

                int v = db.ExecuteNonQueryBySql(String.Format(upsql, (score<pass?1:2) ));
            }
        }

        //  取得待阅的问答题.
        public List<sheet_query_view> GetQueryTopic()
        {
            string sql = "SELECT * FROM sheet_query_view WHERE C_id=" + this.id;
            IDataReader reader = db.ExecuteReaderBySql(sql);
            IList<sheet_query_view> result = DbManager.FillList<sheet_query_view>(reader);
            if (!reader.IsClosed) reader.Close();

            return result.ToList<sheet_query_view>();
        }
    }
}
